package com.scut.campus.utils;

import org.apache.commons.text.similarity.CosineSimilarity;
import org.apache.commons.text.similarity.JaccardSimilarity;

import java.util.HashMap;
import java.util.Map;

public class TextSimilarityUtil {

    // 计算两个文本的相似度，返回满分100的相似度分数
    public static double calculateSimilarity(String text1, String text2) {
        // 1. 计算Jaccard相似度
        JaccardSimilarity jaccardSimilarity = new JaccardSimilarity();
        double jaccardScore = jaccardSimilarity.apply(text1, text2);

        // 2. 计算Cosine相似度
        CosineSimilarity cosineSimilarity = new CosineSimilarity();
        Map<CharSequence, Integer> vectorA = getVector(text1);
        Map<CharSequence, Integer> vectorB = getVector(text2);
        double cosineScore = cosineSimilarity.cosineSimilarity(vectorA, vectorB);

        // 3. 综合两个相似度评分，得出总评分
        double finalScore = (jaccardScore * 50) + (cosineScore * 50); // 各占50%权重
        return finalScore;
    }

    // 将文本转换为词袋向量（Bag-of-Words）
    private static Map<CharSequence, Integer> getVector(String text) {
        String[] words = text.toLowerCase().split("\\s+"); // 按空格分词
        Map<CharSequence, Integer> vector = new HashMap<>();
        for (String word : words) {
            vector.put(word, vector.getOrDefault(word, 0) + 1);
        }
        return vector;
    }
}

